package com.jl15988.simpletools.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jl15988.simpletools.common.annotation.Log;
import com.jl15988.simpletools.common.constant.OperationType;
import com.jl15988.simpletools.common.utils.Result;
import com.jl15988.simpletools.system.domain.entity.User;
import com.jl15988.simpletools.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * 管理员用户控制器
 *
 * @author jl15988
 */
@Slf4j
@Api(tags = "管理员用户接口")
@RestController
@RequestMapping("/admin/v1/user")
@PreAuthorize("hasRole('ADMIN')")
public class AdminUserController {

    @Autowired
    private UserService userService;

    @ApiOperation("分页查询用户列表")
    @GetMapping("/list")
    public Result<IPage<User>> getUserPage(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") Integer size,
            @ApiParam("用户名") @RequestParam(required = false) String username,
            @ApiParam("角色") @RequestParam(required = false) Integer role) {
        IPage<User> pageResult = userService.getUserPage(page, size, username, role);
        return Result.success(pageResult);
    }

    @ApiOperation("获取用户详情")
    @GetMapping("/{userId}")
    public Result<User> getUserDetail(@ApiParam("用户ID") @PathVariable Long userId) {
        User user = userService.getById(userId);
        if (user != null) {
            // 清除敏感信息
            user.setPassword(null);
        }
        return Result.success(user);
    }

    @Log(title = "管理员更新用户角色", operationType = OperationType.UPDATE)
    @ApiOperation("更新用户角色")
    @PutMapping("/{userId}/role/{role}")
    public Result<String> updateUserRole(
            @ApiParam("用户ID") @PathVariable Long userId,
            @ApiParam("角色") @PathVariable Integer role) {
        boolean success = userService.updateUserRole(userId, role);
        return success ? Result.success("更新成功") : Result.error("更新失败");
    }

    @Log(title = "管理员删除用户", operationType = OperationType.DELETE)
    @ApiOperation("删除用户")
    @DeleteMapping("/{userId}")
    public Result<String> deleteUser(@ApiParam("用户ID") @PathVariable Long userId) {
        boolean success = userService.deleteUser(userId);
        return success ? Result.success("删除成功") : Result.error("删除失败");
    }
} 